//
//  ZSWebViewController.swift
//  creativeassistant
//
//  Created by 灵工邦 on 2025/2/13.
//

import UIKit
import WebKit

class ZSWebViewController: ZSBaseViewController {
    
    var linkUrl: String?
    
    lazy var backButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "back"), for: .normal)
        button.adjustsImageWhenHighlighted = false
        button.addTarget(self, action: #selector(goBack(_:)), for: .touchUpInside)
        return button
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor(hexString: "#222222")
        label.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
        return label
    }()
    
    lazy var navigationView: UIView = {
        let navigationView = UIView()
        navigationView.backgroundColor = .clear
        let titleView = UIView()
        navigationView.addSubview(titleView)
        titleView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        
        titleView.addSubview(backButton)
        backButton.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(32)
        }
        
        titleView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(backButton.snp.right)
            make.centerY.equalTo(backButton)
        }
        
        return navigationView
    }()
    
    lazy var progressView: UIProgressView = {
        let progressView = UIProgressView()
        progressView.transform = CGAffineTransform(scaleX: 1.0, y: 1.5)
        progressView.progressTintColor = UIColor.green
        progressView.trackTintColor = .clear
        progressView.progress = 0.1
        return progressView
        
    }()
    
    lazy var webView: WKWebView = {
        let webView = WKWebView()
        webView.navigationDelegate = self
        webView.load(URLRequest(url: URL(string: linkUrl! as String)!))
        return webView
    }()
    
    deinit {
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(self.navigationView)
        self.navigationView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(UIApplication.shared.statusBarFrame.size.height + 44)
        }
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        view.addSubview(webView)
        webView.snp.makeConstraints { make in
            make.top.equalTo(self.navigationView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        view.addSubview(progressView)
        progressView.snp.makeConstraints { make in
            make.top.equalTo(self.webView)
            make.left.right.equalToSuperview()
            make.height.equalTo(1.5)
        }
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if (keyPath == "estimatedProgress") {
            progressView.progress = Float(self.webView.estimatedProgress)
        }
    }
    
    @objc func goBack(_ sender: UIButton) {
        if let navigationController = navigationController, navigationController.viewControllers.count > 1 {
            navigationController.popViewController(animated: true)
        } else if presentingViewController != nil {
            dismiss(animated: true, completion: nil)
        }
    }
}

extension ZSWebViewController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        self.progressView.isHidden = false;
        self.progressView.transform = CGAffineTransformMakeScale(1.0, 1.5);
        self.view.bringSubviewToFront(self.progressView)
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.progressView.progress = 1.0
        self.progressView.isHidden = true
        webView.evaluateJavaScript("document.title") { response, error in
            if let title = response as? String {
                self.titleLabel.text = title
            }
        }
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        let code = (error as NSError).code
        if code == NSURLErrorCancelled {
            self.webView(webView, didFinish: navigation)
        }else {
            self.progressView.isHidden = true
        }
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        self.progressView.isHidden = true
    }
}

